import Taro from '@tarojs/taro';

import { Command } from '../constant';
import { Dispatch } from 'typings';
import { IAllReducerProps } from '../types';
import { getReducerData } from '@/redux/store';
import { extraPathsValue } from '@/redux/util';

import api from 'api';

type strOrNum = number | string;


export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },

    //余额支付 校验密码 改造为发布积分订单2.
    async checckPayPwd() {
      const {
        main: {
          password,
          orderInfo,
          isClick,
          points,
          communityName,
          communityAddress,
          communityId,
          courierStationId,
          courierStationName,
          addressSelect,
          startTime,
          endTime,
          imgUrl,
          requirements,
          points: { integralDeductionSwitch },
        },
      } = getData();
      if (!isClick) {
        return
      }
      if (!communityName) {
        Taro.showToast({
          title: '请选择小区',
          icon: 'none',
          duration: 2000
        })
        return
      }

      if (!courierStationName) {
        Taro.showToast({
          title: '请选择快递站点',
          icon: 'none',
          duration: 2000
        })
        return
      }

      if (!addressSelect?.deliveryAddressId) {
        Taro.showToast({
          title: '请选择送货地址',
          icon: 'none',
          duration: 2000
        })
        return
      }

      if (!startTime) {
        Taro.showToast({
          title: '请选择送达时间',
          icon: 'none',
          duration: 2000
        })
        return
      }

      if (!requirements) {
        Taro.showToast({
          title: '请填写服务需求',
          icon: 'none',
          duration: 2000
        })
        return
      }

      if (!integralDeductionSwitch) {
        Taro.showToast({
          title: '积分不满足使用条件，暂时无法下单',
          icon: 'none',
          duration: 2000
        })
        return
      }
      Taro.showLoading({
        title: '支付中',
      })

      action.commonChange('main.isClick', false)

      let params: any = {}
      params.communityName = communityName
      params.communityAddress = communityAddress
      if (communityId !== '手动选择数据没有id') params.communityId = communityId

      if (courierStationId !== '手动选择数据没有id') params.courierStationId = courierStationId
      params.courierStationName = courierStationName

      params.deliveryAddressId = addressSelect.deliveryAddressId

      params.deliveryTimeBegin = startTime
      params.deliveryTimeEnd = endTime
      if (params.deliveryTimeBegin === '23:00:00') params.deliveryTimeEnd = '23:59:59'

      params.img = imgUrl

      if (points?.maxPoint) params.points = points.maxPoint

      params.requirement = requirements

      try {
        let result = await api.customerBalanceBaseController.checkCustomerPayPwd({ payPassword: password });
        Taro.hideLoading();
        setTimeout(() => {
          action.commonChange('main.isClick', true)
        }, 1000)
        if (result.code === 'K-000000') {
          action.commonChange('main.passwordError', false)

          // 生成积分支付订单
          result = await api.customerDrawCashController.release(params);
          if (result.code !== 'K-000000') {
            await Taro.showToast({
              title: result?.message,
              icon: 'none',
              duration: 2000
            })
            return
          }
          await Taro.showToast({
            title: '发布成功',
            icon: 'success',
            duration: 2000
          })
          setTimeout(() => {
            Taro.reLaunch({
              url: `/pages/package-D/pickupExpressDelivery/index`,
            });
          }, 1000)

          return


          // const type = __TARO_ENV == 'h5' ? 'H5' : 'MINI';
          // // 获取支付渠道id
          // let payInfo = await api.payController.items(type);
          // const balance = payInfo.filter((item) => item.channel === 'Balance')[0];
          // // 发起余额支付
          // let pay_result = await api.payController.balancePay({
          //   channelItemId: balance.id,
          //   escortTradeId: orderInfo.id,
          //   // 支付方式，0：微信支付，1：余额支付，2：积分支付，3：积分+微信，4：积分+余额
          //   escortTradePay: points.integralDeductionSwitch ? '4' : '1',
          //   password
          // });
          // if (pay_result.code === 'K-000000') {
          //   //支付成功
          //   Taro.showToast({ title: '支付成功!' });
          //   Taro.redirectTo({
          //     url: `/pages/package-D/lifeOrders/index?orderType=1`,
          //   });
          // } else {
          //   Taro.showToast({ title: pay_result.message, icon: 'none' });
          // }
        }
        action.commonChange('main.passwordError', true)
        action.commonChange('main.password', '')
      } catch { }
    },

    //发送验证码
    async sendCode() {
      let {
        main: {
          phone,
          isForgetPassword
        },
      } = getData();

      try {
        await api.loginBaseController.balancePayPassword({
          customerAccount: phone,
          isForgetPassword: isForgetPassword,
        });
        Taro.showToast({
          title: '验证码发送成功',
          icon: 'none',
          duration: 2000,
        });
      } catch { }
    },

    // 发送验证码点击下一步
    async doNext() {
      let { phone, code, isForgetPassword } = getData().main;
      const res = await api.customerBalanceBaseController.validatePayCode({
        customerAccount: phone,
        verifyCode: code,
        isForgetPassword,
      });
      if (res) {
        /**验证码校验成功，跳转到下一个页面*/
        action.commonChange('main.showSettingPassword', false);
        action.commonChange('main.showSettingPasswordNext', true);
      } else {
        Taro.showToast({
          title: '验证码错误！',
          icon: 'none',
          duration: 2000,
        });
      }
    },

    // 修改｜设置密码
    async changepwd() {
      let { password, isForgetPassword, code, customerId } = getData().main;
      const regex = /^[A-Za-z0-9]{6,16}$/;
      if (password == '') {
        Taro.showToast({
          title: '请填写密码！',
          icon: 'none',
          duration: 2000,
        });
        return
      } else if (!regex.test(password)) {
        Taro.showToast({
          title: '密码仅限6~16位数字或字母！',
          icon: 'none',
          duration: 2000,
        });
        return
      } else {
        try {
          await api.loginBaseController.passwordByForgot({
            customerId,
            verifyCode: code,
            customerPayPassword: password,
            isForgetPassword
          });
          await Taro.showToast({
            title: '密码设置成功!',
            icon: 'none',
            duration: 2000,
          });
          // 设置了密码拉起支付弹窗
          action.commonChange('main.showSettingPasswordNext', false)
          action.commonChange('main.password', '')
          action.commonChange('main.showPasswordPayment', true)
        } catch { }
      }
    },

    // 发布
    async release() {
      // 或取当前状态值
      let {
        main: {
          communityName,
          communityAddress,
          communityId,
          courierStationId,
          courierStationName,
          addressSelect,
          startTime,
          endTime,
          imgUrl,
          points,
          requirements,
          paymentMethod,
          isPayPwdValid,
          openid,
        },

      } = getData();

      if (!communityName) {
        Taro.showToast({
          title: '请选择小区',
          icon: 'none',
          duration: 2000
        })
        return
      }

      if (!courierStationName) {
        Taro.showToast({
          title: '请选择快递站点',
          icon: 'none',
          duration: 2000
        })
        return
      }

      if (!addressSelect?.deliveryAddressId) {
        Taro.showToast({
          title: '请选择送货地址',
          icon: 'none',
          duration: 2000
        })
        return
      }

      if (!startTime) {
        Taro.showToast({
          title: '请选择送达时间',
          icon: 'none',
          duration: 2000
        })
        return
      }

      if (!requirements) {
        Taro.showToast({
          title: '请填写服务需求',
          icon: 'none',
          duration: 2000
        })
        return
      }

      let params: any = {}
      params.communityName = communityName
      params.communityAddress = communityAddress
      if (communityId !== '手动选择数据没有id') params.communityId = communityId

      if (courierStationId !== '手动选择数据没有id') params.courierStationId = courierStationId
      params.courierStationName = courierStationName

      params.deliveryAddressId = addressSelect.deliveryAddressId

      params.deliveryTimeBegin = startTime
      params.deliveryTimeEnd = endTime
      if (params.deliveryTimeBegin === '23:00:00') params.deliveryTimeEnd = '23:59:59'

      params.img = imgUrl

      if (points?.maxPoint) params.points = points.maxPoint

      params.requirement = requirements

      // // 生成订单
      // const result = await api.customerDrawCashController.release(params);
      // if (result?.payPrice === 0) {
      //   // 0元订单直接跳转订单列表
      //   Taro.redirectTo({
      //     url: `/pages/package-D/lifeOrders/index?orderType=1`,
      //   });
      //   return
      // }
      // action.commonChange('main.orderInfo', result)
      // console.log(result, '<<<<生成订单')

      // if (paymentMethod === 'wallet') {
      //   // 当支付方式为钱包支付时
      //   // 1.未设置密码拉起设置密码弹窗
      //   if (!isPayPwdValid) {
      //     action.commonChange('main.showSettingPassword', true)
      //     return
      //   } else {
      //     // 设置了密码拉起支付弹窗
      //     action.commonChange('main.password', '')
      //     action.commonChange('main.showPasswordPayment', true)
      //   }
      // } else {
      //   // 拉起微信支付
      //   let context = await api.payController.eswxPayUnifiedorderForLittleProgram({
      //     storeId: result.storeId,
      //     escortTradeId: result.id,
      //     // 支付方式，0：微信支付，1：余额支付，2：积分支付，3：积分+微信，4：积分+余额
      //     escortTradePay: points.integralDeductionSwitch ? '3' : '0',
      //     openid
      //   });

      //   const { timeStamp, nonceStr, signType, paySign } = context;
      //   await Taro.requestPayment({
      //     //@ts-ignore
      //     timeStamp,
      //     nonceStr,
      //     package: context.package,
      //     signType,
      //     paySign,
      //     success: async (res) => {
      //       //微信支付成功的回调
      //       Taro.showToast({ title: '支付成功!' });
      //       Taro.redirectTo({
      //         url: `/pages/package-D/lifeOrders/index?orderType=1`,
      //       });
      //     },
      //     fail: function (res) { },
      //   });

      // }
    },

    // 发布积分订单1.
    async releasePoints() {
      action.commonChange('main.showExpenseDetails', false)
      // 或取当前状态值
      let {
        main: {
          communityName,
          communityAddress,
          communityId,
          courierStationId,
          courierStationName,
          addressSelect,
          startTime,
          endTime,
          imgUrl,
          points,
          requirements,
          paymentMethod,
          isPayPwdValid,
          openid,
          deliveryFee,
          points: { integralDeductionSwitch },
          userAgreement
        },

      } = getData();

      if (!userAgreement) {
        Taro.showToast({
          title: '请勾选并阅读同意"代取服务协议"',
          icon: 'none',
          duration: 2000,
        })
        return
      }

      if (!communityName) {
        Taro.showToast({
          title: '请选择小区',
          icon: 'none',
          duration: 2000,
        })
        return
      }

      if (!courierStationName) {
        Taro.showToast({
          title: '请选择快递站点',
          icon: 'none',
          duration: 2000,
        })
        return
      }

      if (!addressSelect?.deliveryAddressId) {
        Taro.showToast({
          title: '请选择送货地址',
          icon: 'none',
          duration: 2000,
        })
        return
      }

      if (!startTime) {
        Taro.showToast({
          title: '请选择送达时间',
          icon: 'none',
          duration: 2000,
        })
        return
      }

      if (!requirements) {
        Taro.showToast({
          title: '请填写服务需求',
          icon: 'none',
          duration: 2000,
        })
        return
      }

      if (!integralDeductionSwitch) {
        Taro.showToast({
          title: '积分不满足使用条件，暂时无法下单',
          icon: 'none',
          duration: 2000,
        })
        return
      }

      let params: any = {}
      params.communityName = communityName
      params.communityAddress = communityAddress
      if (communityId !== '手动选择数据没有id') params.communityId = communityId

      if (courierStationId !== '手动选择数据没有id') params.courierStationId = courierStationId
      params.courierStationName = courierStationName

      params.deliveryAddressId = addressSelect.deliveryAddressId

      params.deliveryTimeBegin = startTime
      params.deliveryTimeEnd = endTime
      if (params.deliveryTimeBegin === '23:00:00') params.deliveryTimeEnd = '23:59:59'

      params.img = imgUrl

      if (points?.maxPoint) params.points = points.maxPoint

      params.requirement = requirements


      if (!isPayPwdValid) {
        action.commonChange('main.showSettingPassword', true)
        return
      } else {
        // 设置了密码拉起支付弹窗
        action.commonChange('main.password', '')
        action.commonChange('main.showPasswordPayment', true)
      }

      // // 生成订单
      // const result = await api.customerDrawCashController.release(params);
      // if (result.code == 'K-000000') {
      //   // 0元订单直接跳转订单列表
      //   Taro.reLaunch({
      //     url: `/pages/package-D/pickupExpressDelivery/index`,
      //   });
      //   return
      // }
      // action.commonChange('main.orderInfo', result)
      // console.log(result, '<<<<生成订单')

      // if (paymentMethod === 'wallet') {
      //   // 当支付方式为钱包支付时
      //   // 1.未设置密码拉起设置密码弹窗
      //   if (!isPayPwdValid) {
      //     action.commonChange('main.showSettingPassword', true)
      //     return
      //   } else {
      //     // 设置了密码拉起支付弹窗
      //     action.commonChange('main.password', '')
      //     action.commonChange('main.showPasswordPayment', true)
      //   }
      // } else {
      //   // 拉起微信支付
      //   let context = await api.payController.eswxPayUnifiedorderForLittleProgram({
      //     storeId: result.storeId,
      //     escortTradeId: result.id,
      //     // 支付方式，0：微信支付，1：余额支付，2：积分支付，3：积分+微信，4：积分+余额
      //     escortTradePay: points.integralDeductionSwitch ? '3' : '0',
      //     openid
      //   });

      //   const { timeStamp, nonceStr, signType, paySign } = context;
      //   await Taro.requestPayment({
      //     //@ts-ignore
      //     timeStamp,
      //     nonceStr,
      //     package: context.package,
      //     signType,
      //     paySign,
      //     success: async (res) => {
      //       //微信支付成功的回调
      //       Taro.showToast({ title: '支付成功!' });
      //       Taro.redirectTo({
      //         url: `/pages/package-D/lifeOrders/index?orderType=1`,
      //       });
      //     },
      //     fail: function (res) { },
      //   });

      // }
    },


    // 切换时间后获取配送费 - 配送费根据时区
    async getDeliveryFee(deliveryTimeBegin, deliveryTimeEnd) {
      if (deliveryTimeBegin === '23:00:00') deliveryTimeEnd = '23:59:59'
      const { totalPrice, basicServiceFee, time_raise } = await api.customerDrawCashController.getDeliveryFee({ deliveryTimeBegin, deliveryTimeEnd });
      action.commonChange('main.deliveryFee', totalPrice)
      action.commonChange('main.basicServiceFee', basicServiceFee)
      action.commonChange('main.timeRaise', time_raise)
      // 更新积分计费
      action._pointInit()
    },

    handleMapData(map) {
      let {
        main: { whoMotherFuckerOpenTheMap },
      } = getData();

      if (whoMotherFuckerOpenTheMap === 'community') {
        action.commonChange('main.communityId', '手动选择数据没有id')
        action.commonChange('main.communityName', map.name)
        action.commonChange('main.communityAddress', map.address)
        action.commonChange('main.showCommunity', false)
        action.commonChange('main.courierStationId', '')
        action.commonChange('main.courierStationName', '')
        action.commonChange('main.courierStation', [])
      }
      if (whoMotherFuckerOpenTheMap === 'courierStation') {
        action.commonChange('main.courierStationId', '手动选择数据没有id')
        action.commonChange('main.courierStationName', map.name)
        action.commonChange('main.showCourierStation', false)
      }
    },

    //积分初始化
    async _pointInit() {
      let { main: { deliveryFee } } = getData()
      Promise.all([
        await api.customerBaseController.getPointsAvailable(),
        await api.systemPointsConfigController.simplify(),
      ])
        .then(([one, two]) => {
          action.commonChange([
            { paths: 'main.points.totalPoint', value: one.pointsAvailable },
            { paths: 'main.points.pointConfig', value: two },
          ]);
        })
        .then(async () => {
          await action._maxPointCal();
        });
    },

    // 最大可用积分逻辑
    async _maxPointCal() {
      let { main: { points, deliveryFee } } = getData()
      // 积分没开
      if (points?.pointConfig?.status !== 1) return
      if (points?.pointConfig?.pointsUsageFlag == 0) {
        // 满overPointsAvailable积分可用
        let { totalPoint, pointConfig: { overPointsAvailable, maxDeductionRate, pointsWorth } } = points
        if (overPointsAvailable <= totalPoint && totalPoint) {
          // 积分最高抵扣订单金额百分比 maxDeductionRate
          // 抵扣系数
          let coefficient = action.divide(maxDeductionRate, 100)
          // 最高抵扣金额
          let maximum = action.multiply(deliveryFee, coefficient)
          maximum = action.toFixedNoRound(maximum, 2)
          // 积分兑换值pointsWorth
          // 最高抵扣金额折算成积分 => 折算积分
          let maximumPoint = action.multiply(maximum, pointsWorth)
          // 这时分为两种情况
          // 1.持有积分大于等于折算积分则最大可用积分依据为折算积分
          if (totalPoint >= maximumPoint) {
            action.commonChange('main.points.maxPoint', maximumPoint)
            action.commonChange('main.points.deductionAmountOfPoints', maximum)
            // 积分够扣自动勾选
            action.commonChange('main.points.integralDeductionSwitch', true)
          } else {
            // 2.持有积分小于折算积分则最大可用积分依据为持有积分
            action.commonChange('main.points.maxPoint', totalPoint)
            let deductionAmountOfPoints = action.divide(totalPoint, pointsWorth)
            deductionAmountOfPoints = action.toFixedNoRound(deductionAmountOfPoints, 2)
            action.commonChange('main.points.deductionAmountOfPoints', deductionAmountOfPoints)
          }
        } else {
          action.commonChange('main.points.maxPoint', 0)
          action.commonChange('main.points.deductionAmountOfPoints', 0)
        }
      } else {
        // 积分使用方式为非订单抵扣时不允许使用
        action.commonChange('main.points.maxPoint', 0)
        action.commonChange('main.points.deductionAmountOfPoints', 0)
      }
    },

    // 计算
    divide(a: strOrNum, b: strOrNum): number {
      const precision = action.getPrecision(a, b);
      const numA = action.toNumber(a, precision);
      const numB = action.toNumber(b, precision);
      return (
        action.multiply(numA, Math.pow(10, precision)) /
        action.multiply(numB, Math.pow(10, precision))
      );
    },
    multiply(a: strOrNum, b: strOrNum): number {
      const precision = action.getPrecision(a, b);
      const numA = action.toNumber(a, precision);
      const numB = action.toNumber(b, precision);
      return (numA * numB) / (precision * precision);
    },
    toFixedNoRound(num: strOrNum, decimalPlaces: number = 0): number {
      const parsedNum = Number(num);
      if (isNaN(parsedNum)) {
        throw new Error('Invalid number input');
      }
      const strNum = parsedNum.toString();
      const dotIndex = strNum.indexOf('.');
      if (dotIndex === -1) return Number(num);
      const truncatedStrNum = strNum.substring(0, dotIndex + decimalPlaces + 1);
      const truncatedNum = Number(truncatedStrNum);
      return truncatedNum;
    },
    getPrecision(a: strOrNum, b: strOrNum): number {
      const precisionA = action.getNumberPrecision(a);
      const precisionB = action.getNumberPrecision(b);
      return Math.pow(10, Math.max(precisionA, precisionB));
    },
    getNumberPrecision(num: strOrNum): number {
      const str = String(num);
      const dotIndex = str.indexOf('.');
      return dotIndex >= 0 ? str.length - dotIndex - 1 : 0;
    },
    toNumber(num: strOrNum, precision: number): number {
      if (typeof num === 'string') {
        return parseFloat(num) * precision;
      }
      return num * precision;
    }
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageAddPickupCourierDMain'),
  };
}
